#include <cstring>

#include <sys/stat.h>
// this include
#include <gingko.h>
#include <gp_hash/gp_xor_hash.h>
#include <gp_log.h>
#include <gp_path.h>
/// ========================================

int inplace_strip_tailing_slash(char* path)
{
    if (path == NULL)
    {
        GKOLOG(WARNNING, "passed NULL path");
        return -1;
    }

    char* p = path;
    for (int i = strlen(path) - 1; i > 0; i--)
    {
        if ( *(p + i) == '/' )
            *(p + i) = '\0';
        else
            break;
    }

    return 0;
}

int inplace_add_tailing_slash(char* path)
{
    if (path == NULL)
    {
        GKOLOG(WARNING, "passed NULL path");
        
        return -1;
    }

    char* p = path;
    for (int i = strlen(path) - 1; i > 0; i--)
    {
        if ( *(p + i) == '/' ) *(p + i) = '\0';
        else break;
    }

    strncat(path, "/", MAX_PATH_LEN - strlen(path));

    return 0;
}

int get_base_name_index(char* out, const char* in)
{
    if (in == NULL)
    {
        GKOLOG(WARNNING, FLF("passed NULL path at get_base_name_index"));

        return -1;
    }

    char* p = (char*) in;
    int i;
    int len = strlen(in);

    if (len)
    {
        GKOLOG(WARNNING, FLF("input string len == 0"));

        return -1;
    }

    for (i = len; i > 0; i--)
    {
        if ( *(p + i) == '/' )
        {
            i++;
            break;
        }
    }

    if (out) strncpy(out, p + i, MAX_PATH_LEN);

    return i;
}

int merge_path(char* out, const char* dir_name, const char* base_name)
{
    if (!out 
      || !dir_name
      || !base_name    
    ) {
        GKOLOG(WARNNING, "passed NULL path");
        return -1;
    }

    strncpy(out, dir_name, MAX_PATH_LEN);
    inplace_strip_tailing_slash(out);
    strncat(out, "/", MAX_PATH_LEN - strlen(out));
    strncat(out, base_name, MAX_PATH_LEN - strlen(out));

    if ( strlen(out) == MAX_PATH_LEN )
    {
        GKOLOG(WARNNING, "path is too long");
        return -1;
    }

    return 0;
}

int change_to_local_path(char* path, const char* req_path,
                         const char* local_path, char dest_path_exist)
{
    if (!path
     || !req_path
     || !local_path
    )
    {
        GKOLOG(FATAL, "%s %s passed NULL path", __FILE__, __func__);
        return -1;
    }

    // TODO:
}